package admin

import (
	"laohuo/dao"
	"laohuo/model"
	"net/http"
	"strconv"

	"github.com/gin-gonic/gin"
)

// 供应商

type Supplier struct{}

func (c *Supplier) List(ctx *gin.Context) {
	params := &struct {
		Page     uint
		Pagesize uint
	}{}
	ctx.ShouldBindQuery(params)
	if params.Page == 0 {
		params.Page = 1
	}
	if params.Pagesize == 0 || params.Pagesize > 100 {
		params.Pagesize = 20
	}

	sus, err := dao.FetchSupplier(params.Page, params.Pagesize)
	if err != nil {
		ctx.String(http.StatusOK, err.Error())
		return
	}

	total, _ := dao.CountSupplier()
	ctx.JSON(http.StatusOK, struct {
		Total int
		Data  []*model.Supplier
	}{total, sus})
}

func (c *Supplier) Add(ctx *gin.Context) {
	params := &struct {
		Name    string
		Address model.Address
		Phone   string
		Email   string
	}{}

	if err := ctx.ShouldBindJSON(params); err != nil {
		ctx.String(http.StatusBadRequest, err.Error())
		return
	}

	su := &model.Supplier{
		Name:    params.Name,
		Address: params.Address,
		Phone:   params.Phone,
		Email:   params.Email,
	}
	if err := dao.AddSupplier(su); err != nil {
		ctx.String(http.StatusInternalServerError, err.Error())
		return
	}
	ctx.JSON(http.StatusOK, su)
}

// Unactive 供应商失活
func (c *Supplier) Unactive(ctx *gin.Context) {
	id, err := strconv.Atoi(ctx.PostForm("id"))
	if err != nil {
		ctx.String(http.StatusBadRequest, err.Error())
		return
	}
	if id == 0 {
		ctx.String(http.StatusBadRequest, "参数错误")
		return
	}

	err = dao.UpdateSupplierStatus(uint(id), model.Unactive)
	if err != nil {
		ctx.String(http.StatusInternalServerError, err.Error())
		return
	}
	ctx.String(http.StatusOK, "OK")
}

// Active 激活供应商
func (c *Supplier) Active(ctx *gin.Context) {
	id, err := strconv.Atoi(ctx.PostForm("id"))
	if err != nil {
		ctx.String(http.StatusBadRequest, err.Error())
		return
	}
	if id == 0 {
		ctx.String(http.StatusBadRequest, "参数错误")
		return
	}

	err = dao.UpdateSupplierStatus(uint(id), model.Active)
	if err != nil {
		ctx.String(http.StatusInternalServerError, err.Error())
		return
	}
	ctx.String(http.StatusOK, "OK")
}
